package com.competition.web.admin.service.impl;

import com.competition.web.entity.Config;
import com.competition.web.admin.mapper.ConfigMapper;
import com.competition.web.admin.service.IConfigService;
import com.basic.service.impl.BaseServiceImpl;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class ConfigServiceImpl extends BaseServiceImpl<Config> implements IConfigService {
	
	private RedisTemplate<String, Config> redisTemplate;
	
	
	@Resource
	public void setRedisTemplate(RedisTemplate<String, Config> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	public ConfigServiceImpl(ConfigMapper mapper) {
		super(mapper);
	}

	protected void insertPropteris(Config data) {
		long time = System.currentTimeMillis() / 1000;
		data.setCreateTime(time);
		data.setUpdateTime(time);
	}

	protected void updatePropteris(Config data) {
		data.setUpdateTime(System.currentTimeMillis() / 1000);
	}

	protected Class<Config> getEntityClass() {
		return Config.class;
	}
	
	
	public <P> int parseUpdate(P param, Class<Config> target) {
		
		int parseUpdate = super.parseUpdate(param, target);
		
		String key = "commuting_hours";
		
		redisTemplate.delete(key);
		
		return parseUpdate;
	}
	

	@Override
	public Config getConfigFromCache() {
		

		String key = "commuting_hours";

		ValueOperations<String, Config> valueOperations = this.redisTemplate.opsForValue();

		Config commutingHoursConfig = valueOperations.get(key);
//
		if (null != commutingHoursConfig) {
			return commutingHoursConfig;
		}

		ConfigMapper config = this.getBaseMapper();
		
		commutingHoursConfig = config.getCommutingHoursConfig(key);
		
		if (null== commutingHoursConfig) {
			
			commutingHoursConfig = new Config();
			
			valueOperations.set(key, commutingHoursConfig, 2, TimeUnit.SECONDS);

			return commutingHoursConfig;
		}

		valueOperations.set(key, commutingHoursConfig, 6, TimeUnit.MINUTES);

		return commutingHoursConfig;
	}
}